<?php

namespace app\common\controller;

use app\common\variable\MsgCode;
use app\common\model\Company as CompanyModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\SpecialTopicEnroll as SpecialTopicEnrollModel;
use app\common\model\SpecialTopicRecruit as SpecialTopicRecruitModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserVipRule;
use think\facade\Db;

class SpecialTopic extends Base
{
    public function index()
    {
        $title = input('get.title', '');
        $data = SpecialTopicRecruitModel::whereLike('title', $title . '%')
            ->where('status', 1)
            ->order(['sort' => 'ASC', 'view' => 'DESC'])
            ->select();
        View::assign('special', $data);
        return view();
    }

    public static function detail($D)
    {
        $specialData = SpecialTopicRecruitModel::where('id', $D['id'])->find();
        if (!$specialData) return false;
        $specialData->company_sum = SpecialTopicEnrollModel::where(['special_id' => $D['id'], 'status' => 1])
            ->count() + $specialData->base_enroll;
        $specialData->jobs_sum = JobsModel::alias('job')
            ->join('special_topic_enroll enroll', 'enroll.company_id=job.company_id')
            ->where(['enroll.special_id' => $D['id'], 'enroll.status' => 1])
            ->count() + $specialData->base_jobs;
        $specialData->resume_sum = JobsDeliveryResumeModel::alias('delivery')
            ->join('special_topic_enroll enroll', 'enroll.company_id=delivery.company_id')
            ->where(['enroll.special_id' => $D['id'], 'enroll.status' => 1])
            ->group('delivery.resume_id')
            ->count();
        $specialData->isSignUp = 1;
        // 实际浏览量
        $specialData->real_view = $specialData['view'];
        // 展示浏览量
        $specialData->view = $specialData->real_view + $specialData->base_view;
        if ($D['role_type'] && $D['company_id'])
            $specialData->isSignUp = SpecialTopicEnrollModel::where(['special_id' => $D['id'], 'company_id' => $D['company_id']])->count();
        $companyData = SpecialTopicEnrollModel::alias('enroll')
            ->where(['nature.alias' => 'company/nature'])
            ->join('company company', 'company.id=enroll.company_id')
            ->join('company_industry industry', 'industry.id=company.industry_id')
            ->join('status_alias nature', 'nature.value=company.nature')
            ->join('status_alias size_type', 'company.size_type=size_type.value')
            ->field(['company.*', 'size_type.title' => 'size_type', 'industry.title' => 'industry', 'nature.title as nature'])
            ->withAttr('logo', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : config('web.imgurl') . config('xy_default_avatar.company_logo');
            })
            ->where('enroll.special_id', $D['id'])
            ->where('enroll.status', 1)
            ->where('size_type.alias', 'company/size_type')
            ->select();
        for ($i = 0; $i < count($companyData); $i++) {
            $item = $companyData[$i];
            $resume_sum = JobsDeliveryResumeModel::where(['company_id' => $item->id])->count();
            $not_resume_sum = JobsDeliveryResumeModel::where(['company_id' => $item->id, 'status' => 0])->count();
            $companyData[$i]->resume_efficiency = ($resume_sum - $not_resume_sum) > 0 ? round(($resume_sum - $not_resume_sum) / $resume_sum * 100) : 0;
            $companyData[$i]->jobs_sum = JobsModel::where(['company_id' => $item->id, 'status' => 1])->count();
        }
        SpecialTopicRecruitModel::where('id', $D['id'])
            ->inc('view')
            ->update();
        return ['content' => $specialData, 'companyList' => $companyData];
    }

    public static function addEnroll($D)
    {
        $special = SpecialTopicRecruitModel::where('id', $D['id'])->find();
        if (empty($special)) {
            return parent::ajaxReturn('专题不存在！', MsgCode::$error);
        }
        if ($special->status != 1) {
            return parent::ajaxReturn('目标专题不是启用状态！', MsgCode::$error);
        }
        if ($special->end_time < time() || $special->start_time > time()) {
            return parent::ajaxReturn('此专题不在报名时间段，无法报名');
        }
        if (empty($D['uid'])) {
            return parent::ajaxReturn('请先登录企业账号再报名！', MsgCode::$error);
        }
        if ($D['role_type'] != 1) {
            return parent::ajaxReturn('只有企业用户需要报名！', MsgCode::$error);
        }
        $company = CompanyModel::where('uid', $D['id'])->find();
        if (empty($company)) {
            return parent::ajaxReturn('请先绑定企业！', MsgCode::$error);
        }
        $existsEnroll = SpecialTopicEnrollModel::where(['special_id' => $special->id, 'company_id' => $company->id])->find();
        if ($existsEnroll) {
            if ($existsEnroll->status == 0) {
                return parent::ajaxReturn('你已报名，但未被管理员通过，请勿重复报名', MsgCode::$error);
            } else {
                return parent::ajaxReturn('你已报名，且已通过，请勿重复报名', MsgCode::$error);
            }
        }
        $userInfo = UserInfoModel::where('uid', $D['id'])->find();
        if ($userInfo->score < $special->point_cost) {
            return parent::ajaxReturn('报名需要扣除' . $special->point_cost . '积分，你的积分不足！');
        }
        $enrollNumber = SpecialTopicEnrollModel::where('special_id', $special->id)->count();
        if ($enrollNumber >= $special->max_limit) {
            return parent::ajaxReturn('此专题招聘企业报名名额已满，不能再继续报名', MsgCode::$error);
        }
        $vipLevels = explode(',', $special['vip_level']);
        $userVip = UserVipRule::where('uid', $D['id'])->find();
        if (!in_array($userVip->company_vip_level, $vipLevels)) {
            return parent::ajaxReturn('会员类型不在允许报名列表', MsgCode::$error);
        }
        // if ($userVip->company_vip_time >= time()) {
        //     return parent::ajaxReturn('你的会员权益已过期', MsgCode::$error);
        // }
        try {
            Db::startTrans();
            // 条件均满足，扣除积分，写入报名表
            $userInfo->dec('score', $special->point_cost)->save();
            $enroll = [
                'special_id' => $special->id,
                'company_id' => $company->id,
                'status' => 0
            ];
            SpecialTopicEnrollModel::create($enroll);
            Db::commit();
        } catch (\Throwable $ex) {
            Db::rollback();
            return parent::ajaxReturn('无法创建报名数据，积分已返还', MsgCode::$error);
        }
        return parent::ajaxReturn('报名成功！');
    }
}
